<template>
  <div class="lianxi_se">
    <m-header modile-title="练习7" go-back="true"></m-header>
    <div class="input_box">
      <select name="" id="" @change="choseType" v-model="typeText">
        <option :value='item.value' v-for="(item,index) in options" :key="index">{{item.typeName}}</option>
      </select>
    </div>
    <div class="content_show" v-show="typeText === 'xiao' || typeText === 'ting' || typeText === 'zhi'">
      <div v-show="typeText === 'xiao'" style="width: 100%;height: 200px;background: red"></div>
      <div v-show="typeText === 'ting'" style="width: 100%;height: 200px;background: orange"></div>
      <div v-show="typeText === 'zhi'" style="width: 100%;height: 200px;background: yellowgreen"></div>
    </div>

    <div class="input_box">
      <div
        style="width: 200px;height: 60px;border:1px solid #333;text-align: center;line-height: 40px;padding-bottom: 20px"
        @click="slectbtn">{{divText}}
      </div>
      <ul class="select_box" v-show="slectShhow">
        <li v-for="(items,index) in options" :key="index" @click="liClick(items.value,items.typeName)">
          {{items.typeName}}
        </li>
      </ul>
    </div>
    <div class="content_show" v-show="divValue === 'xiao' || divValue === 'ting' || divValue === 'zhi'">
      <div v-show="divValue === 'xiao'" style="width: 100%;height: 200px;background: green"></div>
      <div v-show="divValue === 'ting'" style="width: 100%;height: 200px;background: aqua"></div>
      <div v-show="divValue === 'zhi'" style="width: 100%;height: 200px;background: blue"></div>
    </div>

    <form action="uploadImage" method="post" enctype="multipart/form-data">
      <input type="file" name="file" multiple="multiple" accept="image/*">
      <input type="submit">
    </form>


    <div>指明需要多张图片</div>
    <input v-if="isOther" type="file" @change="onFileChange" multiple accept='image/*'>

    <!--上传图片展示-->
    <div v-if="isOther" style="width: 100%;" v-show="isOther">
      <img :src="im" alt="" v-for="(im,ims) in imagesLrz" :key="ims">
    </div>
    <button v-if="isWX" style="width: 200px;height: 60px" @click="addImage()">微信上传图片</button>
    <div v-if="isWX" style="width: 200px;height: 50px;border: 1px solid #ff0000">我是微信显示的图片</div>
  </div>
</template>
<script>
  import mHeader from '../../../../components/header'
  import lrz from 'lrz'
  import wx from 'weixin-js-sdk'
  import qs from 'qs'

  export default {
    data() {
      return {
        typeText: 'xiao',
        slectShhow: false,
        divText: '点击查看不同类别',
        divValue: 'xiao',
        options: [
          {id: 1, typeName: '消防电梯', value: 'xiao'},
          {id: 2, typeName: '停车收费', value: 'ting'},
          {id: 3, typeName: '植被维护', value: 'zhi'}
        ],
        imagesLrz: [],
        isWX: true, // 微信浏览器
        isOther: true, // 其他浏览器
        images: {
          localId: [],
          iosLocalId: []
        },
        maxSize: 0,
        ready: false,
        isIOS: false,
        serverId: [],

      }
    },
    created() {
      if (this.isWeiXin()) {
        this.isWX = true
        this.isOther = false
      } else {
        this.isWX = false
        this.isOther = true
      }
      const urlLink = 'https://ynwx.zgwyzxw.cn/index.php/wx/wx_jssdk/getSignPackage'
      var data = {
        url: window.location.href.split('#')[0]
      }
      this.$http.post(urlLink, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
        if (res.data.code === 200) {
          wx.config({
            debug: false,
            appId: res.data.data.appId,
            nonceStr: res.data.data.nonceStr,
            rawString: res.data.data.rawString,
            signature: res.data.data.signature,
            timestamp: res.data.data.timestamp,
            jsApiList: ['chooseImage', 'previewImage', 'getLocalImgData', 'uploadImage']
          })
          this.ready = true
        }
      })
    },
    methods: {
      choseType() {
        // console.log(this.typeText)
      },
      slectbtn() {
        this.slectShhow = true
      },
      liClick(value, name) {
        // console.log(value)
        this.slectShhow = false
        this.divText = name
        this.divValue = value
      },
      //判断是否是微信浏览器
      isWeiXin() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          return true;
        } else {
          return false;
        }
      },
      // 图片上传(不是微信的上传图片)
      onFileChange(e) {
        let files = e.target.files || e.dataTransfer.files
        this.createImage(files)
        // console.log(e)
      },
      createImage(file, e) {
        // console.log(file)
        for (var i = 0; i < file.length; i++) {
          lrz(file[i], {quality: 0.4})
            .then((rst) => {
              let img = new Image()
              img.src = rst.base64
              this.imagesLrz.push(rst.base64)
              // this.$emit('getImage', this.imagesLrz)
              // return rst
              console.log(this.imagesLrz)
            })
            .always(function () {
              // 清空文件上传控件的值
              e.target.value = null
            })
        }
      },
      addImage() {
        if (this.ready) {
          var self = this
          var currentSize = this.images.localId.length
          if (self.isIOS) {
            if (this.images.iosLocalId.length > 5) {
              Toast({
                message: '图片不能超过6张',
                position: 'middle',
                duration: 1000
              })
              return
            }
          } else {
            if (this.images.localId.length > 5) {
              Toast({
                message: '图片不能超过6张',
                position: 'middle',
                duration: 1000
              })
              return
            }
          }
          wx.chooseImage({
            count: 6 - currentSize, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              self.images.localId = self.images.localId.concat(res.localIds)
              if (window.__wxjs_is_wkwebview) {
                self.isIOS = true

                function readImages() {
                  wx.getLocalImgData({
                    localId: self.images.localId[currentSize],
                    success: function (res) {
                      var localData = res.localData
                      localData = localData.replace('jgp', 'jpeg')
                      self.images.iosLocalId.push(localData)
                      currentSize++
                      if (currentSize < self.images.localId.length) {
                        readImages()
                      }
                    },
                    fail: (res) => {
                      alert(res.errMsg)
                    }
                  })
                }

                readImages()
              }
              self._upload(currentSize)
            },
            fail: (err) => {
              console.log(err)
            }
          })
        }
      },
      _upload(i) {
        // var localId = localIds.shift()
        wx.uploadImage({
          localId: this.images.localId[i], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: (res) => {
            i++
            this.serverId.push(res.serverId) // 返回图片的服务器端ID
            this.$emit('getImage', this.serverId)
            if (i < this.images.localId.length) {
              setTimeout(() => {
                this._upload(i)
              }, 100)
            }
          }
        })
      },
    },
    components: {
      mHeader
    }
  }
</script>
<style lang="scss">
  .lianxi_se {
    width: 100%;
    padding-top: 64px;
    .input_box {
      width: 100%;
      height: 50px;
      background: #fff;
      select {
        width: 200px;
        height: 40px;
        option {
          text-align: center;
        }
      }
      .select_box {
        width: 200px;
        /*height: 40px;*/
        /*border: 1px solid #333333;*/
        li {
          width: 200px;
          height: 60px;
          text-align: center;
          line-height: 60px;
          background: rebeccapurple;
        }
      }
    }
  }
</style>
